package flex.cc.drive.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.CommonUtils;
import flex.cc.drive.dao.OrderDriverDao;
import flex.cc.drive.dto.DriverInterfaceLogEntity;
import flex.cc.drive.dto.DriverRemarkEntity;
import flex.cc.drive.dto.OrderDriverEntity;
import flex.cc.drive.service.DriverCancelService;
import flex.cc.drive.service.DriverInterfaceLogService;
import flex.cc.drive.service.DriverRemarkService;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2022年1月17日上午11:13:25
 * @desc 代驾取消业务实现层
 */
@Service("driverCancelService")
public class DriverCancelServiceImpl implements DriverCancelService{
	private static final Logger logger = LoggerFactory.getLogger(DriverCancelServiceImpl.class);
	@Resource
    private OrderDriverDao orderDriverDao;
	@Resource
    private StoreCouponDao storeCouponDao;
	@Resource
	private DriverVerifyService driverVerifyService;
	@Resource
    private DriverRemarkService remarkService;
	@Resource
    private DriverInterfaceLogService logService;
    @Autowired
	private APIConfigUtil apiConfigUtil;
//	@Value("${redeemcode.source}")
//    private String source;
//	@Value("${api.config.key}")
//    private String key;
//	@Value("${api.config.cancelBespeakUrl}")
//    private String cancelUrl;
	
	/**
	 * 
	 * @author WANGCONG
	 * 2022年1月19日下午16:09:29
	 * @desc 代驾取消
	 * @version 2.0
	 */
	@Override
	public Map<String, String> driverCancel_V2(Map<String, String> postMap) {
		Map<String, String> resultMap = new HashMap<>();
		String orderNo = postMap.get("orderNo");
		String orderId = postMap.get("orderId");
		if(PublicUtil.isEmpty(orderNo)) {
			resultMap.put("code", "01");
			resultMap.put("msg", "服务单号orderNo不能为空");
			return resultMap;
		}
		if(PublicUtil.isEmpty(orderId)) {
			resultMap.put("code", "01");
			resultMap.put("msg", "订单号orderId不能为空");
			return resultMap;
		}
		//根据订单号查询车服是否存在此条数据
		OrderDriverEntity driverEntity = orderDriverDao.findByOrderNo(orderNo);
		if(driverEntity == null){
			resultMap.put("code", "01");
			resultMap.put("msg", "代驾订单不存在");
			return resultMap;
		}
		String cancelFlag = driverEntity.getCancelFlag(); //取消标识，0-可取消、1-不可取消
		if(PublicUtil.isNotEmpty(cancelFlag) && "1".equals(cancelFlag)) {
			resultMap.put("code", "01");
			resultMap.put("msg", "代驾订单不可重复取消");
			return resultMap;
		}
		DriverInterfaceLogEntity logEntity = new DriverInterfaceLogEntity();
		Map<String,Object> requestBody = new HashMap<String,Object>();
		
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("couponNum", orderId);
		StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(params);
		String provider = couponEntity.getServer();
		
		String source = apiConfigUtil.getApiConfig(provider, "disponse_code");
		requestBody.put("source", source);
		Map<String,String> encry = new HashMap<String,String>();
		encry.put("source", source);
		encry.put("orderId", orderId);
		String request = "";
		try {
			String key = apiConfigUtil.getApiConfig(provider, "drive_decode");
			String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
			String data = DriveDESUtil.driverEncrypt(CommonUtils.toJSONString(encry), key,key3Des);
			requestBody.put("data", data);
			String logId = UUID.randomUUID().toString().replace("-", "");
	    	logEntity.setDataId(logId);
	    	logEntity.setOrderNo(orderNo);
	    	logEntity.setOrderId(orderId);
	    	logEntity.setInterfaceName("代驾取消接口");
			logEntity.setRequestTime(new Date());
			request = CommonUtils.toJSONString(requestBody);
			logEntity.setRequestBody(request);
		} catch(Exception e){
			resultMap.put("code", "01");
			resultMap.put("msg", "代驾取消报文加密报错");
			return resultMap;
		}
		//成功报文：{"resultCode":"success","resultDesc":"成功","data":null}
		String cancelUrl = apiConfigUtil.getApiConfig(provider, "annInsp_cancel");
		logger.info("代驾取消接口url ==" + cancelUrl);
		logger.info("代驾取消接口请求报文 ==" + request);
		
		String resultJson = CommonUtils.driverPost(cancelUrl, request);
		logEntity.setResponseTime(new Date());
        logEntity.setResponseBody(resultJson);
        logEntity.setCreateTime(new Date());
        logService.insert(logEntity);
        String remarkId = UUID.randomUUID().toString().replace("-", "");
    	DriverRemarkEntity remarkEntity = new DriverRemarkEntity();
    	remarkEntity.setDataId(remarkId);
    	remarkEntity.setOrderNo(driverEntity.getOrderNo());
    	remarkEntity.setOrderId(driverEntity.getOrderId());
//    	remarkEntity.setOrderNo("ZXDJ001");
//    	remarkEntity.setOrderId("KQ001");
    	
    	remarkEntity.setLink("代驾取消接口");
    	remarkEntity.setCreateTime(new Date());
    	remarkEntity.setCreator("");
    	remarkEntity.setUpdater("");
    	remarkEntity.setIsDelete(0);
		if(resultJson != null){
			try {
        		JSONObject json = JSONObject.parseObject(resultJson);
        		String resultCode = json.get("resultCode").toString();
        		if("success".equals(resultCode)){ //调用成功
        			//更新代驾单cancelFlag：0-可取消、1-不可取消 为1，防止用户多次取消
        			Map<String, Object> orderParam = new HashMap<>();
					orderParam.put("orderNo", orderNo);//服务单号
					orderParam.put("cancelFlag", "1");
					orderDriverDao.updateByParams(orderParam);
        			resultMap.put("code", "00");
    				resultMap.put("msg", "代驾取消成功");
    				remarkEntity.setUpdateTime(new Date());
    		    	remarkEntity.setStatus("0");
    		    	remarkEntity.setRemark("代驾取消接口成功");
    		    	remarkService.insert(remarkEntity);
        		}else{
        			resultMap.put("code", "01");
        			Object resultDesc = json.get("resultDesc");
        			String message = "";
        			if(resultDesc!=null){
        				message = resultDesc.toString();
        			}
        			remarkEntity.setUpdateTime(new Date());
    		    	remarkEntity.setStatus("1");
    		    	remarkEntity.setRemark("代驾取消接口失败:"+message);
    		    	remarkService.insert(remarkEntity);
        			resultMap.put("msg", "代驾取消失败:"+message);
        		}
			} catch (Exception e) {
				//返回参数格式有误，解析异常，记录轨迹
				resultMap.put("code", "01");
				resultMap.put("msg", "代驾取消失败:响应报文解析异常");
				remarkEntity.setUpdateTime(new Date());
		    	remarkEntity.setStatus("1");
		    	remarkEntity.setRemark("代驾取消接口失败:响应报文解析异常");
		    	remarkService.insert(remarkEntity);
			}
		}else{
			resultMap.put("code", "01");
			resultMap.put("msg", "代驾取消失败:响应报文为空");
			remarkEntity.setUpdateTime(new Date());
	    	remarkEntity.setStatus("1");
	    	remarkEntity.setRemark("代驾取消接口失败:响应报文为空");
	    	remarkService.insert(remarkEntity);
		}
		return resultMap;
	}
	
	
	/**
	 * 
	 * @author WANGCONG
	 * 2022年1月17日上午11:13:36
	 * @desc 代驾取消
	 */
	/*盛大请求报文：
	{
	    "source":"渠道号-商户渠道标识",
	    "besCode":"预约编号",
	    "isRights":"取消是否扣权益",
	    "hexSign":"加密串-MD5.MD5Encode(this.source+this.besCode+this.key)"
	}
	盛大响应报文：
	{
    	"resultCode": "SUCCESS"
    	"resultDesc": "成功,系统处理正常"
	}
	--------------------------------------------
	车服响应报文：
	{
    	"code": "00"
    	"resultDesc": "成功"
	}
	{
    	"code": "01"
    	"resultDesc": "失败"
	}
	*/
	@Override
	public Map<String, String> driverCancel(Map<String, String> postMap) {
		Map<String, String> resultMap = new HashMap<>();
		//根据预约编号查询车服是否存在此条数据
		OrderDriverEntity driverEntity = orderDriverDao.findByOrderNo(postMap.get("orderNo"));
		if(driverEntity == null){
			resultMap.put("code", "01");
			resultMap.put("msg", "预约编号不存在");
			return resultMap;
		}
		
		String logId = UUID.randomUUID().toString().replace("-", "");
    	DriverInterfaceLogEntity logEntity = new DriverInterfaceLogEntity();
    	logEntity.setDataId(logId);
    	logEntity.setOrderNo(postMap.get("orderNo"));
    	logEntity.setOrderId(postMap.get("orderId"));
    	logEntity.setInterfaceName("代驾取消接口");
    	String requestBody = CommonUtils.toJSONString(postMap);
		logEntity.setRequestTime(new Date());
		logEntity.setRequestBody(requestBody);
		String resultJson = CommonUtils.driverPost("盛大代驾取消接口", requestBody);
		logEntity.setResponseTime(new Date());
        logEntity.setResponseBody(resultJson);
        logEntity.setCreateTime(new Date());
        logService.insert(logEntity);
        
        String remarkId = UUID.randomUUID().toString().replace("-", "");
    	DriverRemarkEntity remarkEntity = new DriverRemarkEntity();
    	remarkEntity.setDataId(remarkId);
    	remarkEntity.setOrderNo(driverEntity.getOrderNo());
    	remarkEntity.setOrderId(driverEntity.getOrderId());
    	remarkEntity.setLink("代驾取消接口");
    	remarkEntity.setCreateTime(new Date());
    	remarkEntity.setCreator("");
    	remarkEntity.setUpdater("");
    	remarkEntity.setIsDelete(0);
		if(resultJson != null){
			try {
        		JSONObject json = JSONObject.parseObject(resultJson);
        		String resultCode = json.get("resultCode").toString();
        		if("SUCCESS".equals(resultCode)){ //调用成功
        			resultMap.put("code", "00");
    				resultMap.put("msg", "成功");
    				remarkEntity.setUpdateTime(new Date());
    		    	remarkEntity.setStatus("0");
    		    	remarkEntity.setRemark("代驾取消接口成功");
    		    	remarkService.insert(remarkEntity);
    				String orderStatus = json.get("orderStatus").toString(); //1：取消可用，5：取消完成
    				Map<String, Object> orderParam = new HashMap<>();
					orderParam.put("orderNo", postMap.get("orderNo"));//服务单号(预约编号)
					orderParam.put("updateTime", new Date());
    				if("5".equals(orderStatus)){//需调用上游核销通知接口
    					orderParam.put("status", "06");//06-取消核销
    					orderDriverDao.updateByParams(orderParam);
    					Map<String, String> verifyMap = new HashMap<String, String>();
    					verifyMap.put("couponNum", driverEntity.getOrderId()); //归属卡券码
    					verifyMap.put("packageCode", driverEntity.getPackageCode()); //归属服务包编码
    					verifyMap.put("orderNo", postMap.get("orderNo")); //预约编号
    					verifyMap.put("orderId", driverEntity.getOrderId());
    					driverVerifyService.verifyNotice(verifyMap);
    				}else{
    					orderParam.put("status", "05");//05-预约取消
    					orderDriverDao.updateByParams(orderParam);
    				}
        		}else{
        			resultMap.put("code", "01");
        			String message = json.get("resultDesc").toString();
        			remarkEntity.setUpdateTime(new Date());
    		    	remarkEntity.setStatus("1");
    		    	remarkEntity.setRemark("代驾取消接口失败:"+message);
    		    	remarkService.insert(remarkEntity);
        			resultMap.put("msg", message);
        		}
			} catch (Exception e) {
				//返回参数格式有误，解析异常，记录轨迹
				resultMap.put("code", "01");
				resultMap.put("msg", "取消接口响应报文解析异常");
				remarkEntity.setUpdateTime(new Date());
		    	remarkEntity.setStatus("1");
		    	remarkEntity.setRemark("代驾取消接口失败:响应报文解析异常");
		    	remarkService.insert(remarkEntity);
			}
		}else{
			resultMap.put("code", "01");
			resultMap.put("msg", "取消接口响应报文为空");
			remarkEntity.setUpdateTime(new Date());
	    	remarkEntity.setStatus("1");
	    	remarkEntity.setRemark("代驾取消接口失败:响应报文为空");
	    	remarkService.insert(remarkEntity);
		}
		return resultMap;
	}

}
